import React, { useState, useRef, useEffect } from 'react';
import { Table, TableProps } from 'antd';
import { ColumnsType } from 'antd/es/table';
import './ResizableTable.css';

interface ResizableTableProps<T> extends TableProps<T> {
  columns: ColumnsType<T>;
}

const ResizableTable = <T extends Record<string, any>>({
  columns,
  ...props
}: ResizableTableProps<T>) => {
  const [tableColumns, setTableColumns] = useState<ColumnsType<T>>(columns);
  const tableRef = useRef<HTMLDivElement>(null);
  const resizingRef = useRef<{
    columnIndex: number;
    startX: number;
    startWidth: number;
  } | null>(null);

  useEffect(() => {
    setTableColumns(columns);
  }, [columns]);

  const handleMouseDown = (e: React.MouseEvent, columnIndex: number) => {
    e.preventDefault();
    e.stopPropagation();
    
    const startX = e.clientX;
    const table = tableRef.current?.querySelector('.ant-table-tbody') as HTMLElement;
    if (!table) return;

    const headerCells = tableRef.current?.querySelectorAll('.ant-table-thead th');
    if (!headerCells || !headerCells[columnIndex]) return;

    const startWidth = (headerCells[columnIndex] as HTMLElement).offsetWidth;
    
    resizingRef.current = {
      columnIndex,
      startX,
      startWidth,
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
    document.body.style.cursor = 'col-resize';
    document.body.style.userSelect = 'none';
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (!resizingRef.current) return;

    const { columnIndex, startX, startWidth } = resizingRef.current;
    const deltaX = e.clientX - startX;
    const newWidth = Math.max(50, startWidth + deltaX); // 最小宽度50px

    setTableColumns(prevColumns => {
      const newColumns = [...prevColumns];
      if (newColumns[columnIndex]) {
        newColumns[columnIndex] = {
          ...newColumns[columnIndex],
          width: newWidth,
        };
      }
      return newColumns;
    });
  };

  const handleMouseUp = () => {
    resizingRef.current = null;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
    document.body.style.cursor = '';
    document.body.style.userSelect = '';
  };

  // 为每个列添加调整手柄
  const enhancedColumns = tableColumns.map((column, index) => {
    const originalTitle = column.title;
    return {
      ...column,
      title: () => (
        <div className="resizable-header">
          <span>{originalTitle as React.ReactNode}</span>
          <div
            className="resize-handle"
            onMouseDown={(e) => handleMouseDown(e, index)}
          />
        </div>
      ),
    };
  });

  return (
    <div ref={tableRef} className="resizable-table-container">
      <Table
        {...props}
        columns={enhancedColumns}
        scroll={{ x: 'max-content', ...props.scroll }}
      />
    </div>
  );
};

export default ResizableTable;